var SkyView = function() {
	var self = this;
	var starsLayer = {};
	this.pathList = []
	this.selectedStars = []
	this.allStarsList = []
	this.currentPath = 0
	this.controlsView = new ControlsView()
	this.initialPos = undefined;
	this.movableSegment = undefined;
	this.lastSegment = undefined;
	this.MODE = "NAV" // | NAV | SELECTION | SELECTING

	wmax = 5000,
	hmax = 2400;
	this.changed = new signals.Signal();

	this.createPath = function() {
		var p = new Path();
		p.strokeColor = '#ffffff';
		$("#color_value").val('ffffff')
		p.strokeWidth = 1.5;
		p.saturation = 0.1
		return p
	}

	this.init = function(data) {
		self.controlsView.init();
		self.pathList[self.currentPath] = self.createPath();
		self.pathList[self.currentPath].strokeColor = '#ffffff'
		self.pathList[self.currentPath].strokeWidth = 1.5;
		self.controlsView.changed.add(controlsChanged);

		load_bg()		
	}


	function controlsChanged(type) {
		switch (type) {
			case 'add':
				self.initSelection()
			break;

			case 'color':
				if(self.pathList[self.currentPath])self.pathList[self.currentPath].strokeColor = $("#color_value").val()
		 		setTimeout(function() {
		 			// console.log("color picked")
		 			$("#input_username").focus()
		 			document.getElementById('color').color.hidePicker()
		 		;}, 300 )

			break;

			case 'save':
				self.saveConstellation();
			break;

			case 'redo':
				self.redoSelection()
			break;

			case 'cancel':
				self.finishSelection()
			break;

			case 'done':
				self.doneSelection()
			break;
		}
	}

	this.initStars = function(data) {
 		// console.log('[Skyview] initStars()')
 		starsLayer = new Layer();
 		for (var i = 0; i < data.length; i++) {
			var item = data[i]
			var group = new Group();
			var bg = new Path.Circle({
				center: [item.x,item.y],
				radius: 15,
				fillColor: new Color(0, 0, 0,0),
				strokeColor: '#004d90',
				strokeCap : 'round',
				dashArray : [3, 3],
				strokeWidth: 1,
				opacity: 0
			})
			bg.data.id = item.id
			bg.data.type = 'star'
			bg.name = item.id
			bg.rotate(5)
			

			var circle = new Path.Star({
				center: [item.x, item.y],
				points: Math.floor(random(3,7)),
				radius1: random(1.2,2.1),
				radius2: random(.1,.3),
				fillColor: 'white'
			});
			// if(circle.position.y > 1400)circle.opacity = 0.4
			circle.locked = true;
			group.data.id = item.id;
			group.data.type = 'star';
			group.name = item.id;
			group.addChild(bg);
			group.addChild(circle);
			group.opacity = 0;
			self.allStarsList.push(group);
			//
			
		}
		
		// for (var i = 0; i < self.allStarsList.length; i++) {
 	// 		b = paper.view.bounds.contains(self.allStarsList[i].position)
 	// 		if(b) {
 	// 			self.allStarsList[i].opacity = 0;	
 	// 		}
 	// 	};
		this.render()

		

		load_mask()
		self.changed.dispatch('stars_loaded')
 	}
 
 	this.show = function() {
 		for (var i = 0; i < self.allStarsList.length; i++) {
 			b = paper.view.bounds.contains(self.allStarsList[i].position)
 			if(b) {
 				
 				TweenMax.to(self.allStarsList[i],2, {opacity:1, delay: random(0.2, 0.4)})	
 			}else {
 				self.allStarsList[i].opacity = 1;
 			}
 		};

 		//release the navigation at this point
		initNav()
		self.controlsView.state('NAV');
 		
 	}

	this.initSelection = function() {
 		self.MODE = 'SELECTION'
 		self.changed.dispatch(self.MODE)
 		project.activeLayer.attach('click', star_onClick)
 		project.activeLayer.attach('mouseenter', star_onMouseEnter)
 		project.activeLayer.attach('mouseleave', star_onMouseLeave)
 		
 		for (var i = 0; i < this.allStarsList.length; i++) {
 			var group = this.allStarsList[i]
 			group.children[0].opacity = 1
		}

		self.controlsView.state('SELECTION')
	
 	}

 	this.stopSelection = function() {
 		paper.tool.detach('mousemove', onMouseMove)
 		project.activeLayer.detach('click', star_onClick)
 		project.activeLayer.detach('mouseenter', star_onMouseEnter)
 		project.activeLayer.detach('mouseleave', star_onMouseLeave)
 		for (var i = 0; i < this.allStarsList.length; i++) {
 			 var group = this.allStarsList[i]
 			group.children[0].opacity = 0
		}
 		
 	}

 	this.saveConstellation = function()  {
		var c = new ConstellationItem()
		c.name = $('#input_const_name').val()
		c.username = $('#input_username').val()
		// console.log('$("#color_value").val()', $("#color_value").val())
		c.color = $("#color_value").val()
		c.stars = self.selectedStars

		//get an image based on the model
		constellationsView.add(c,0)
		c.file = constellationsView.image(c)
		constellationsModel.post(c)
		self.finishSelection()
		
 	}
 	
 	this.showShare = function() {
 		// console.log('[MainView] showShare()')
 		self.controlsView.state('SHARE');
 	}

 	this.redoSelection = function() {
 		removeStar();
 	
 	}

 	this.doneSelection = function() {
 		// console.log(self.pathList[self.currentPath].segments.length)
 		if(self.pathList[self.currentPath].segments.length > 2) {
 			self.stopSelection();
 			paper.tool.detach('mousemove', onMouseMove)
			self.pathList[self.currentPath].lastSegment.remove()

 			self.controlsView.state('DONE');
 		}
 	}

 	this.finishSelection = function() {
 		/* selection canceled */
 		this.stopSelection();
 		self.selectedStars = [];
		self.initialPos = undefined
		paper.tool.detach('mousemove', onMouseMove)
		
		self.pathList[self.currentPath].removeSegments()
		// self.pathList[self.currentPath].remove()
		// self.currentPath++

		// self.pathList[self.currentPath] = self.createPath();
		self.MODE = 'NAV'
		self.changed.dispatch(self.MODE)
		self.controlsView.state('NAV')
 	}

 	function removeStar() {
		//removes the last segment
		paper.tool.detach('mousemove', onMouseMove)
		// console.log('self.pathList[self.currentPath].children',self.selectedStars.length,  self.selectedStars.length)
		// paper.tool.detach('mousemove', onMouseMove)
		if(!self.pathList[self.currentPath].isEmpty()) {
			self.movableSegment.remove();
			self.lastSegment.remove();

			if(self.pathList[self.currentPath].segments.length > 0) {
				self.lastSegment = self.pathList[self.currentPath].lastSegment
			
				//add movable
				self.pathList[self.currentPath].add(self.lastSegment);	
				self.movableSegment = self.pathList[self.currentPath].lastSegment
			}

			self.selectedStars.pop()
			paper.tool.attach('mousemove', onMouseMove)


		}else {
			self.stopSelection();
 	 		self.selectedStars = [];
			self.initialPos = undefined
			self.pathList[self.currentPath].removeSegments()
			// self.pathList[self.currentPath].remove()
			// self.currentPath++
			// self.pathList[self.currentPath] = self.createPath();
			self.initSelection()
		}
	}

 	

 	var mouseSpeed=0;
 	var container_point = {}
 	function initNav() {
		var hammertime = Hammer(canvas).on("dragstart", function(e) {
	        bmousedown = true;
	        TweenMax.killTweensOf(container_point)
	        mx = e.gesture.center.pageX;
	        my = e.gesture.center.pageY;
	    });

	    var hammertime = Hammer(canvas).on("dragend", function(e) {
	        bmousedown = false
	        
   			// mouseSpeed = Math.max( e.gesture.velocityX,  e.gesture.velocityY)
   			var dx =  mouseSpeed * e.gesture.deltaX//*.3
   			var dy = mouseSpeed * e.gesture.deltaY //*.3
   			


   			var n = new Point()
   				n.x = paper.view.center.x - dx
   				n.y = paper.view.center.y - dy

   			if(n.x  < (paper.view.bounds.width * .5) ) n.x = (paper.view.bounds.width * .5) 
			if(n.y < (paper.view.bounds.height * .5)) n.y = (paper.view.bounds.height * .5)

			if(n.x > (wmax - paper.view.bounds.width * .5))  n.x = wmax - (paper.view.bounds.width * .5)
			if(n.y  > (hmax - paper.view.bounds.height * .5))  n.y = hmax - (paper.view.bounds.height * .5)

			container_point = new Point(paper.view.center)
	 		// console.log(n)
	 		var duration =  mouseSpeed
	 		TweenMax.killTweensOf(container_point)
	 		TweenMax.to(container_point, duration, {x: n.x, y:n.y,ease:Quart.easeOut, onUpdate:function() { paper.view.center = container_point; self.render()}, onComplete: self.render} )
	    });

	    var hammertime = Hammer(canvas).on("drag", function(e) {
	        e.gesture.preventDefault()

   			var x, y;
   			x = e.gesture.center.pageX;
   			y = e.gesture.center.pageY;
   			if(bmousedown) {
   				var dx =  (mx - x) //*.3
   				var dy = (my - y) //*.3
   				mouseSpeed = Math.max(Math.abs(dx), Math.abs(dy)) *0.02
   				// mouseSpeed =  mouseSpeed

   				var n = new Point()
   				n.x = paper.view.center.x + dx
   				n.y = paper.view.center.y + dy

   			
   				if(n.x  < (paper.view.bounds.width * .5) ) n.x = (paper.view.bounds.width * .5) 
   				if(n.y < (paper.view.bounds.height * .5)) n.y = (paper.view.bounds.height * .5)

   				if(n.x > (wmax - paper.view.bounds.width * .5))  n.x = wmax - (paper.view.bounds.width * .5)
   				if(n.y  > (hmax - paper.view.bounds.height * .5))  n.y = hmax - (paper.view.bounds.height * .5)
   				
   				// console.log(n)
   				// paper.view.center = n
   				mx = e.gesture.center.pageX;
   				my = e.gesture.center.pageY;
   				TweenMax.killTweensOf(container_point)
   				paper.view.center = n
   				container_point = n
		 		
		 		// TweenMax.set(container_point, {x: n.x, y:n.y,ease:Quart.easeOut, onComplete:function() { paper.view.center = container_point; self.render()}} )

   				// mousePos.x = event.point.x - paper.view.bounds.x
   				// mousePos.y = event.point.y - paper.view.bounds.y
   				self.render()
   			}
   			
	    });

		// var hammertime = Hammer(canvas).on("pinchin", function(e) {
		// 	e.gesture.preventDefault()
		// 	if(paper.view.zoom >0.5) paper.view.zoom -= 0.1
		// });

		// var hammertime = Hammer(canvas).on("pinchout", function(e) {
		// 	e.gesture.preventDefault()
		//     if(paper.view.zoom <1.2) paper.view.zoom += 0.1
		// });
	}

 	this.moveSky = function(px, py, duration) {
 		// console.log("moveSky")
 		var n = new Point(px, py)

 		if(n.x  < (paper.view.bounds.width * .5) ) n.x = (paper.view.bounds.width * .5) 
 		if(n.y < (paper.view.bounds.height * .5)) n.y = (paper.view.bounds.height * .5)

 		if(n.x > (wmax - paper.view.bounds.width * .5))  n.x = wmax - (paper.view.bounds.width * .5)
 		if(n.y  > (hmax - paper.view.bounds.height * .5))  n.y = hmax - (paper.view.bounds.height * .5)
 		
 		var c = new Point(paper.view.center)
 		// console.log(n)
 		
 		TweenMax.to(c, duration, {x: n.x, y:n.y, onUpdate:function() { paper.view.center = c; self.render()}, onComplete: self.render} )
 	}

 	this.render = function() {
 		var b = false
 		for (var i = 0; i < self.allStarsList.length; i++) {
 			b = paper.view.bounds.contains(self.allStarsList[i].position)
 			self.allStarsList[i].visible = b
 		};
 		self.controlsView.resize()
 	}

 	this.createLimit = function() {
 		this.stopSelection();
 		self.moveSky(self.initialPos.x, self.initialPos.y,1)

 		project.activeLayer.attach('click', star_onClick)
 		project.activeLayer.attach('mouseenter', star_onMouseEnter)
 		project.activeLayer.attach('mouseleave', star_onMouseLeave)

 		for (var i = 0; i < this.allStarsList.length; i++) {
 			var group = this.allStarsList[i];
 			if(group.position.getDistance(self.initialPos) < 150) {
	 			// group.attach('click', star_onClick)
	 			// group.attach('mouseenter', star_onMouseEnter)
	 			// group.attach('mouseleave', star_onMouseLeave)
	 			group.children[0].opacity = 1
 			}

		}

		self.controlsView.resize()
		
 	}

 	function onMouseMove(event) {
 		// console.log('onMouseMove')
 		if (event.point.getDistance(self.initialPos) < 150) {
			self.movableSegment.point = event.point
		}else {
			self.movableSegment.point = self.lastSegment.point 
		}
	}
 	

 
 	function star_onClick(event) {
 		if(event.target.data.type != 'star') {
 			return
 		}
 		if(event.target.opacity == 0) {
 			return
 		}
 		paper.tool.detach('mousemove', onMouseMove)
 
		if(self.initialPos==undefined) {
			self.controlsView.state('SELECTING')
			self.initialPos = event.target.position
			self.createLimit();
		}

		if(self.pathList[self.currentPath]){


			if(self.movableSegment)self.movableSegment.remove()

			self.pathList[self.currentPath].add(event.target.position);
			self.lastSegment = self.pathList[self.currentPath].lastSegment

			self.pathList[self.currentPath].add(event.target.position);	
			self.movableSegment = self.pathList[self.currentPath].lastSegment

			
		}
		paper.tool.attach('mousemove', onMouseMove)
		self.selectedStars.push(event.target.name)
	};
	
	function star_onMouseEnter(event) {
		if(event.target.data.type != 'star') {
 			return
 		}
		event.target.strokeColor = '#FFFFFF'
		// event.target.bringToFront()
	};

	function star_onMouseLeave(event) {
		if(event.target.data.type != 'star') {
 			return
 		}
		event.target.strokeColor = '#004d90'
		// event.target.rotate(-90)
		// TweenMax.to(event.target, 0.4, {opacity:1, onUpdate:function() { event.target.rotate(-5)}})
	};

 	function load_bg() {
		var img = document.createElement("img");
		img.src = "/assets/images/sky.jpg";
		img.id = "sky"
		document.body.appendChild(img);
		$('#sky').hide()
		var raster = new Raster('sky');
		raster.visible = false;
		raster.scale(1);
		var that = this

		
		raster.position = paper.view.center;
		img.onload = function() {
			// console.log('[SkyView] background image loaded', $(img).height())
			raster.position.x = wmax *.5
			raster.position.y  = hmax *.5
			raster.sendToBack()
			$('#sky').remove()
			raster.visible = true
			// load_mask()
		}
	}

	function load_mask() {
 		var img = document.createElement("img");
 		img.src = "/assets/images/mask-tinified.png";
 		img.id = "mask"
 		document.body.appendChild(img);
 		$('#mask').hide()
 		var raster = new Raster('mask');
 		
 		raster.scale(1);
 		// raster.locked = true;
 		raster.bringToFront()
 		raster.bringToFront()
 		var that = this
 		raster.position = paper.view.center;
 		img.onload = function() {
 			// console.log('[SkyView] mask image loaded', $(img).height())
 			raster.position.x = wmax *.5
 			raster.position.y  = hmax - $(img).height() *.5
 			raster.visible = true
 			$('#mask').remove()
 			
 			self.changed.dispatch('background_loaded')
 		}
 	}


 
    return this

}
